package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.Participant;
import com.alipay.api.request.AlipayFundTransUniTransferRequest;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.apiResult.Result;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.pay.ali.AlipayConfig;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.core.page.PagePlus;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.system.aikeService.ToZhtcApiService;
import com.ruoyi.system.domain.ZsyyUser;
import com.ruoyi.system.mapper.ZsyyUserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.system.bo.ZsyyGetcashAddBo;
import com.ruoyi.system.bo.ZsyyGetcashQueryBo;
import com.ruoyi.system.bo.ZsyyGetcashEditBo;
import com.ruoyi.system.domain.ZsyyGetcash;
import com.ruoyi.system.mapper.ZsyyGetcashMapper;
import com.ruoyi.system.vo.ZsyyGetcashVo;
import com.ruoyi.system.service.IZsyyGetcashService;
import com.ruoyi.system.mapper.ZsyyGetcashMapper;

import java.util.*;

import org.springframework.beans.factory.annotation.Autowired;
/**
 * 提现记录Service业务层处理
 *
 * @author wangghua
 * @date 2021-07-14
 */
@Service
public class ZsyyGetcashServiceImpl extends ServicePlusImpl<ZsyyGetcashMapper, ZsyyGetcash> implements IZsyyGetcashService {
	public static final Logger logger = LoggerFactory.getLogger(ZsyyGetcashServiceImpl.class);
	@Value("${pay.ali.alipayCertPublicKey}")
	private String alipayCertPublicKey;
	@Value("${pay.ali.alipayRootCert}")
	private String alipayRootCert;
	@Value("${pay.ali.appCertPublicKey}")
	private String appCertPublicKey;
    @Autowired
    private ZsyyGetcashMapper iZsyyGetcashMapper;
    @Autowired
    private ZsyyUserMapper userMapper;

    @Override
    public ZsyyGetcashVo queryById(Long id){
        return getVoById(id, ZsyyGetcashVo.class);
    }

    @Override
    public TableDataInfo<ZsyyGetcashVo> queryPageList(ZsyyGetcashQueryBo bo) {
		Page<ZsyyGetcashVo> page = iZsyyGetcashMapper.queryPageList(PageUtils.buildPage(),bo);
		return PageUtils.buildDataInfo(page);
    }

    @Override
    public List<ZsyyGetcashVo> queryList(ZsyyGetcashQueryBo bo) {
        return listVo(buildQueryWrapper(bo), ZsyyGetcashVo.class);
    }

    private LambdaQueryWrapper<ZsyyGetcash> buildQueryWrapper(ZsyyGetcashQueryBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ZsyyGetcash> lqw = Wrappers.lambdaQuery();
        lqw.eq(StrUtil.isNotBlank(bo.getOrderNo()), ZsyyGetcash::getOrderNo, bo.getOrderNo());
        lqw.eq(bo.getStatus() != null, ZsyyGetcash::getStatus, bo.getStatus());
        lqw.like(StrUtil.isNotBlank(bo.getName()), ZsyyGetcash::getName, bo.getName());
        return lqw;
    }

    @Override
    public Boolean insertByAddBo(ZsyyGetcashAddBo bo) {
		bo.setCreatetime(new Date());
        ZsyyGetcash add = BeanUtil.toBean(bo, ZsyyGetcash.class);
        validEntityBeforeSave(add);
        return save(add);
    }

    @Override
    public AjaxResult updateByEditBo(ZsyyGetcashEditBo bo) {
		try {
			ZsyyGetcash getCash1 = iZsyyGetcashMapper.selectById(bo.getId());
			ZsyyUser user = userMapper.selectById(getCash1.getUserId());
			CertAlipayRequest req = new CertAlipayRequest();
			req.setSignType("RSA2");
			req.setAppId(AlipayConfig.APP_ID);
			req.setServerUrl("https://openapi.alipay.com/gateway.do");
			req.setFormat("JSON");
			req.setPrivateKey(AlipayConfig.PRIVATE_KEY);
			req.setCertPath(appCertPublicKey);
			req.setAlipayPublicCertPath(alipayCertPublicKey);
			req.setRootCertPath(alipayRootCert);
			//req.setCertContent(AliUtils.getInst().getAppCertPublicKey());
			//req.setAlipayPublicCertContent(AliUtils.getInst().getAlipayCertPublicKey());
			//req.setRootCertContent(AliUtils.getInst().getAlipayRootCert());
			req.setCharset("utf-8");
			AlipayClient alipayClient = new DefaultAlipayClient(req);
			AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
			Map<String, Object> refundParam = new HashMap<String, Object>();
			refundParam.put("biz_scene", "DIRECT_TRANSFER");    //单笔无密转账到支付宝/银行卡, B2C现金红包;
			refundParam.put("out_biz_no", getCash1.getOrderNo());    //商户网站唯一订单号
			refundParam.put("product_code","TRANS_ACCOUNT_NO_PWD");   //转到支付宝
			refundParam.put("order_title", "提现");   //该笔订单允许的最晚付款时间，逾期将关闭交易
			refundParam.put("trans_amount",getCash1.getExtractPrice()/100d+"" );//订单总金额，单位为元，精确到小数点后两位
			Participant payee_info = new Participant();
			payee_info.setIdentity(getCash1.getAccount());
			payee_info.setName(getCash1.getName());
			payee_info.setIdentityType("ALIPAY_LOGON_ID");
			refundParam.put("payee_info",payee_info);
			String biz = JSON.toJSONString(refundParam);
			request.setBizContent(biz);
			AlipayFundTransUniTransferResponse response =null;
			response = alipayClient.certificateExecute(request);
			if(response.isSuccess()){
				logger.info("调用成功");
				getCash1.setExtractId(response.getOrderId());
				getCash1.setPayFundId(response.getPayFundOrderId());
				getCash1.setStatus(2);
				getCash1.setUpdatetime(new Date());
				getCash1.setCheckDes(bo.getCheckDes());
				iZsyyGetcashMapper.updateById(getCash1);
				user.setBalance(user.getBalance()-getCash1.getApplyPrice());
				userMapper.updateById(user);
			} else {
				getCash1.setExtractId(response.getOrderId());
				getCash1.setPayFundId(response.getPayFundOrderId());
				getCash1.setStatus(3);
				getCash1.setUpdatetime(new Date());
				getCash1.setCheckDes("找不到匹配的账号");
				iZsyyGetcashMapper.updateById(getCash1);
				logger.info("调用失败");
				return AjaxResult.error("找不到匹配的账号");
			}
			return AjaxResult.success("审核成功");
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		return AjaxResult.error("审核失败");
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(ZsyyGetcash entity){
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return removeByIds(ids);
    }
}
